package org.tool.core.lang.convert.converter;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.tool.core.lang.convert.Converter;

import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES;

/**
 * 将给定的对象转换为JSON格式的字符串
 *
 * @author 李坤
 * @date 2022/7/10 16:33
 */
public class Object2JsonStringConverter extends Converter<String> {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        // 序列化时忽略未知字段
        objectMapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 表示始终包含属性的值，与属性的值无关
        objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
    }

    @Override
    public String convert(Object source) throws Exception {
        return objectMapper.writeValueAsString(source);
    }

}
